package com.doit.day03;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.roaringbitmap.RoaringBitmap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

//1.每5s输出一次当前来了多少用户(去重)  uv
public class _02_消费者练习题3_bitMap {
    public static void main(String[] args) {
        //创建一个roaring bitmap对象
        RoaringBitmap bitmap = RoaringBitmap.bitmapOf();

        //读取数据的线程
        new Thread(new MyThread_bitmap(bitmap,"event-log")).start();
//        定时任务
        Timer timer = new Timer();
        timer.schedule(new MyTask_bitmap(bitmap),5000,5000);

    }
}

class MyThread_bitmap implements Runnable{
    private RoaringBitmap bitmap;
    private KafkaConsumer<String, String> consumer;
    public MyThread_bitmap(RoaringBitmap bitmap,String ... topics ){
        this.bitmap = bitmap ;
        Properties props = new Properties();
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "HaoRang1");
        props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        //创建kafka的消费者
        consumer = new KafkaConsumer<String, String>(props);
        consumer.subscribe(Arrays.asList(topics));
    }
    @Override
    public void run() {

        //拉取数据
        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Integer.MAX_VALUE));
            for (ConsumerRecord<String, String> record : poll) {
                String json = record.value();
                EventLog eventLog = JSON.parseObject(json, EventLog.class);
                int guid = eventLog.getGuid();
                bitmap.add(guid);

            }
        }
    }
}


class MyTask_bitmap extends TimerTask{
    private RoaringBitmap bitmap;
    public MyTask_bitmap(RoaringBitmap bitmap){
        this.bitmap = bitmap ;
    }
    @Override
    public void run() {
        //返回一下set 截止到现在为止他的长度嘛
        System.out.println("截止到现在为止，uv数为："+bitmap.getCardinality());

    }
}